package api.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BusinessHandler extends ChannelInboundHandlerAdapter {


  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    log.info("request -> {}", msg);

    FullHttpRequest httpRequest = (FullHttpRequest) msg;
    ByteBuf content = httpRequest.content();
    log.info("body -> {}", content.toString(CharsetUtil.UTF_8));

    String uri = httpRequest.uri();

    ByteBuf buf = Unpooled.copiedBuffer("hello world 没有找到对应的命令", CharsetUtil.UTF_8);

    if (uri.startsWith("/create")) {

      //创建索引
      IndexDemo.createDocument();
      buf = Unpooled.copiedBuffer("createIndex end", CharsetUtil.UTF_8);

    } else if (uri.startsWith("/search")) {
      //查询flush 的索引
      String search = IndexDemo.search();
      buf = Unpooled.copiedBuffer(search, CharsetUtil.UTF_8);
    } else if (uri.startsWith("/reOpen")) {
      //刷新一次 通过 openIfChanged 更新 DirectoryReader 对象
      String s = IndexDemo.reOpenIfChanged();
      buf = Unpooled.copiedBuffer("refresh search end " + s, CharsetUtil.UTF_8);
    } else if (uri.startsWith("/flush")) {
      // 不能查询到新增的索引,但是index 目录下生成了两个文件 fdt 和 fdx,但是不能被检索
      IndexDemo.flush();
      buf = Unpooled.copiedBuffer("flush end", CharsetUtil.UTF_8);
    } else if (uri.startsWith("/commit")) {
      IndexDemo.commit();
      buf = Unpooled.copiedBuffer("commit end", CharsetUtil.UTF_8);
    } else if (uri.startsWith("/close")) {
      IndexDemo.close();
      buf = Unpooled.copiedBuffer("close end", CharsetUtil.UTF_8);
    }

    //响应体
    FullHttpResponse response
            = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "test/plain;charset=UTF-8");

    ChannelFuture channelFuture = ctx.writeAndFlush(response);
    channelFuture.addListener(ChannelFutureListener.CLOSE); //关闭

    httpRequest.release(); //释放 ByteBuf

  }

}
